/**
 * abssqr.com Inc.
 * Copyright (c) 2017-2021 All Rights Reserved.
 */

package cn.dalgen.mybatis.gen.utils;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;

/**
 * @author xiachenxiang
 * @version com.abssqr.plat.common.util.utils: AbsThreadUtil.java, v 0.1 2021-04-08 4:46 PM xiachenxiang Exp $
 */
public class DalgenThreadUtil {

    public static <T> void run(List<T> datas, final Function<T, Void> function, int threadSize) {
        if (CollectionUtils.isNotEmpty(datas)) {
            BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(datas.size());
            // 2. 初始化线程池
            ThreadPoolExecutor executor = new ThreadPoolExecutor(threadSize, threadSize, 24 * 60 * 60, TimeUnit.SECONDS,
                queue);
            final CountDownLatch countDownLatch = new CountDownLatch(datas.size());
            for (final T data : datas) {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            System.out.println(Thread.currentThread().getName());
                            function.apply(data);
                        } finally {
                            System.out.println(Thread.currentThread().getName()+"- finished");
                            countDownLatch.countDown();
                        }
                    }
                });
            }
            try {//所有都执行完毕
                countDownLatch.await();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                executor.shutdown();
            }
        }
    }
}
